package com.hzy.admin.services.impl;

import com.hzy.admin.repository.mapper.MemberMapper;
import com.hzy.admin.repository.entity.Member;
import com.hzy.admin.repository.entity.system.SysUser;
import com.hzy.toolkit.Tools;
import com.hzy.toolkit.UploadFileUtils;
import com.hzy.admin.services.IMemberService;
import com.hzy.admin.services.system.ISysUserService;
import com.hzy.admin.models.vo.system.TableVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzy
 * @since 2020-04-28
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    protected final ISysUserService sysUserService;

    public MemberServiceImpl(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @Override
    public TableVo<Map<String, Object>> findList(Integer page, Integer size, Member search) {
        Page<Map<String, Object>> iPage = new Page<>(page, size);
        List<Map<String, Object>> data = this.baseMapper.getList(iPage, search);
        return TableVo.page(iPage, data);
    }

    @Override
    public Map<String, Object> findById(String id) {
        Map<String, Object> map = new HashMap<>();

        Member model = Tools.nullSafe(this.baseMapper.selectById(id), new Member());
        SysUser user = this.sysUserService.getBaseMapper().selectById(model.getUserId());

        map.put("id", id);
        map.put("model", model);
        map.put("user", Tools.nullSafe(user, new SysUser()));
        return map;
    }

    @Override
    @Transactional
    public String insertOrUpdate(Member model, final MultipartFile filePhoto, final MultipartFile[] files) {
        if (filePhoto != null) {
            try {
                model.setPhoto(UploadFileUtils.save(filePhoto));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (files != null && files.length > 0) {
            ArrayList<String> paths = new ArrayList<>();
            try {
                paths = UploadFileUtils.save(files);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!paths.isEmpty()) {
                model.setFilePath(Tools.joinString(paths, ","));
            }
        }

        this.saveOrUpdate(model);
        return model.getId();
    }

    @Override
    @Transactional
    public void deleteByIds(List<String> ids) {
        this.removeByIds(ids);
    }
}
